import React, { Component,useState,useRef,useEffect} from 'react'
import {withRouter} from "react-router-dom"
import "./index.scss"
import { Tabs, Form, Input, Button, Checkbox ,Row,Col,message} from 'antd';
import { UserOutlined, LockOutlined,AppleOutlined,PhoneOutlined,ExperimentOutlined,MessageOutlined } from '@ant-design/icons';
import {reg}  from "../../utils/validate.js"
import { request } from '../../api';
import mobxdata from "../../mobx/data"
const { TabPane } = Tabs;
const {phone,pwd}  = reg;
export default class LoginCom extends Component {

    componentDidMount(){
        request.getToken()
        .then(res=>{
            console.log(res);
        })
    }

    render() {


        return (
            <div className="loginBg">
                <div className="login">
                    <Tabs defaultActiveKey="1" >
                        <TabPane tab="密码登录" key="1">
                            <PasswordLogin history={this.props.history}></PasswordLogin>
                        </TabPane>
                        <TabPane tab="验证码登录" key="2">
                            <CodeLogin history={this.props.history}></CodeLogin>
                        </TabPane>

                    </Tabs>
                </div>
            </div>
        )
    }
}
const layout = {
    labelCol: { span: 0 },
    wrapperCol: { offset:4,span: 16 },
  };

@withRouter
class PasswordLogin extends Component {
    componentDidMount(){
       if(localStorage.getItem("isAutoLogin")){
           var userinfo = JSON.parse(localStorage.getItem('userinfo'))
        console.log(this.myform);
        this.myform.setFieldsValue({...userinfo,remember:true})
       }
    }
    onFinish=(value)=>{
        console.log(value);
        request.login(value)
        .then(res=>{
          if(res.code==200){
            console.log(res);
            this.props.history.push("./main")
            localStorage.setItem("userinfo",JSON.stringify(res.result))
            localStorage.setItem("token",res.token)
            // mobxdata.changeuserinfo(res.result)
          }
        }) 
        value.remember ? localStorage.setItem("isAutoLogin",value.remember) : localStorage.setItem("isAutoLogin",'')
}
onFinishFailed=()=>{
    message.error('请输入有效的登录信息')
}
    render() {
        
        return (
            <div>

                <Form
                  {...layout}
                    name="normal_login"
                    className="login-form"
                    initialValues={{}}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    ref={el=>this.myform=el}
                >
                    <Form.Item
                        name="phone"
                        rules={[{ required: true, message: 'Please input your phne!' }, {pattern:reg.phone,message:"请输入正确的手机号"}]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="phone" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: 'Please input your Password!' }, {pattern:reg.pwd,message:"6-16位数字加字母"}]}
                    >
                        <Input.Password
                            prefix={<LockOutlined className="site-form-item-icon" />}
                           
                            placeholder="Password"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Form.Item  name="remember" valuePropName="checked" noStyle>
                            <Checkbox>记住密码</Checkbox>
                        </Form.Item>

                     
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" block htmlType="submit" className="login-form-button">
                        登录
                                </Button>
                            
                    </Form.Item>
                </Form>
                        

            </div>
        )
    }
}

const layout2 ={
    labelCol:{
        span:6
    },
    wrapperCol:{
        span:16
    }
}


const tailLayout = {
    wrapperCol: { offset: 6, span: 16 },
};

function CodeLogin({history}){

    const  [flag,setFlag] = useState(true)
    let  [count,setCount] = useState(10)
    const [disabled,setDosabled] = useState(true)
    const myForm = useRef()

    const onFinish=(value)=>{
        console.log(value);
        request.verifycaptcha(value)
        .then(res=>{
            if(res.code==200){
                history.push("./main")
                localStorage.setItem("userinfo",JSON.stringify(value))
                localStorage.setItem("token",res.token)
                // mobxdata.changeuserinfo(res.result)
                localStorage.setItem("isAutoLogin")
            }
        })
    }
    let timer =null;
    const checkPhoneValue=()=>{
        console.log(myForm.current);
        var phoneValue = myForm.current.getFieldValue('phone')
        setDosabled(!reg.phone.test(phoneValue))
    }

    const onFinishFailed=()=>{

    }
    const countDown=()=>{
      
        setFlag(false)
        timer = setInterval(()=>{
            if(count>0){
                setCount(--count)
                setFlag(false)
            }else{
                clearInterval(timer)
                timer = null
                count = 10
                setFlag(true)
            }
        },1000)
        gotoGetCaptch()
    }
     const gotoGetCaptch=()=>{
        var phone = myForm.current.getFieldValue('phone')
        request.sendcaptcha({
            phone
        })
        .then(res=>{
            console.log(res);
        })
    }
    useEffect(()=>{
       if(localStorage.getItem("userinfo")){
        let userinfo = JSON.parse(localStorage.getItem('userinfo'))
        myForm.current.setFieldsValue({
            phone:userinfo.phone
        })
        setDosabled(!phone.test(userinfo.phone))
       }
    },[]) 
    return (
        <div>
            <Form
                {...layout2}
                name="normal_login"
                className=" "
                initialValues={{  }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                ref={myForm}
            >
                <Form.Item
                    label="手机号码"
                    name="phone"
                    rules={[{ required: true, message: '请输入你的手机号码' },
                {pattern:reg.phone,message:"请输入正确的手机号"}
                ]}
                >
                    <Input onChange={checkPhoneValue}  prefix={<PhoneOutlined  className="site-form-item-icon" />} placeholder="请输入你的手机号码" />
                </Form.Item>
                <Form.Item
                    label="验证码"  
                    name="captcha"
                 
                    rules={[{ required: true, message: '请输入验证码' }]}
                >
                    
                    <Row>
                        <Col span={14}>
                        <Input    maxLength={4} prefix={<MessageOutlined className="site-form-item-icon" />} placeholder="请输入验证码" />
                        </Col>
                        <Col span={6} >
                           {
                               flag? <Button type="danger" disabled={disabled} onClick={countDown}>发送验证码</Button>: <Button disabled> {count} S  </Button>
                           }
                        </Col>
                    </Row>
                </Form.Item>

                <Form.Item {...tailLayout}>
                    <Button  style={{marginTop:20}} type="danger" block  htmlType="submit" className="login-form-button">
                        立即登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}